package main

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

type UserInfo struct {
	ID     uint64
	Name   string
	Gender string
	Hobby  string
}

type User struct {
	gorm.Model
	Name         string
	Age          sql.NullInt64
	Birthday     *time.Time
	Email        string  `gorm:"type:varchar(100);unique_index"`
	Role         string  `gorm:"size:255"`        // 设置字段大小为255
	MemberNumber *string `gorm:"unique;not null"` // 设置会员号（member number）唯一并且不为空
	Num          int     `gorm:"AUTO_INCREMENT"`  // 设置 num 为自增类型
	Address      string  `gorm:"index:addr"`      // 给address字段创建名为addr的索引
	IgnoreMe     int     `gorm:"-"`               // 忽略本字段
}

func main() {

	db, err := gorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/gorm_demo?charset=utf8mb4&parseTime=true&loc=Local"), &gorm.Config{})

	if err != nil {
		panic("failed to connect database")
	}

	//UserInfoDemo(db)

	UserDemo(db)
}

func UserDemo(db *gorm.DB) {

	db.AutoMigrate(&User{})

}

func UserInfoDemo(db *gorm.DB) {
	db.AutoMigrate(&UserInfo{})

	ui := UserInfo{1, "艾伦·耶格尔", "男", "自由"}
	db.Create(ui)

	var u UserInfo
	db.First(&u)

	fmt.Printf("UserInfo:%v\n", u)

	// update
	u.Hobby = u.Hobby + ",三笠"
	db.Updates(u)

	var u2 UserInfo
	db.First(&u2)

	fmt.Printf("UserInfo:%v\n", u2)
}
